<template>
    <div class="body">
        <div class="newlist">
            <div class="header">
                <div class="title">
                    论坛
                </div>
            </div>
            <Tabs :headerHeight="40" style="height:80px;margin-bottom: 20px">
                <TabPanel :title="'Tab1'">
                    <template slot="header">
                        <div class="tt-inner">
                            <p>专题分类</p>
                        </div>
                    </template>
                    <div class="category_tags">
                        <span style="font-size: 12px">选择分类板块：</span>
                        <el-tag size="small" :type="tag.value==searchModel.categoryId ?'success' : 'warning'"
                                style="margin-right: 10px;cursor:pointer;"
                                v-for="tag in options" :key="tag.value" @click="tagSelect(tag)">
                            {{tag.label}}
                        </el-tag>
                    </div>

                </TabPanel>
            </Tabs>
            <div class="tool">
                <div class="toolleft">
                    <Form ref="form" :model="searchModel">
                        <TextBox inputId="keyword" name="keyword" v-model="searchModel.keyword"
                                 style="margin-right: 10px"></TextBox>
                        <LinkButton :disabled="false" iconCls="icon-search" @click="search()"
                                    style="margin-right: 10px">查找文章
                        </LinkButton>
                    </Form>
<!--                    <LinkButton :disabled="false" iconCls="icon-filter" @click="searchTop()">高级查找</LinkButton>-->
                </div>
                <div class="toolright">
                    <LinkButton :disabled="false" iconCls="icon-add" @click="addArticle()">新增文章</LinkButton>
                </div>

            </div>
            <div class="datagrid">

            </div>
            <!--            数据表格-->
            <DataGrid :data="articlelist" :clickToEdit="true" selectionMode="cell" :rowHeight="rowHeight"
                      editMode="cell" :style="{height:scrollerHeight}" @rowDblClick="datagridDoubleClick"
                      :columnResizing="true"
            >
                <GridColumn field="articlecategory" title="分类板块" align="center" :editable="false"
                            width="10%"></GridColumn>
                <GridColumn field="articletitle" title="文章标题" align="center" width="45%"></GridColumn>
                <GridColumn field="author" title="作者" align="center" width="10%">
                </GridColumn>
                <GridColumn field="date" title="发布日期" align="center" width="10%">

                </GridColumn>
                <GridColumn field="pageview" title="浏览次数" width="5%" align="center"></GridColumn>
                <GridColumn title="操作" width="15%" align="center" >
                    <template slot="body" slot-scope="scope">
                        <el-button  @click="articleEdit(scope.row.id)" size="small" type="success" style="font-size: 12px;margin: 10px">编 辑</el-button>
                        <el-button  type="warning" @click="articleDelete(scope.row.id)" size="small" style="font-size: 12px;margin: 10px">删 除</el-button>
                    </template>
                </GridColumn>

            </DataGrid>
            <Pagination :total="total" :pageSize="pageSize" :pageNumber="currentPage" :layout="layout1"
                        :displayMsg="displayMsg" @pageChange="onPageChange($event)"></Pagination>
        </div>
        <!--        新增文章-->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                :fullscreen="true"
        >
            <div class="dialogdiv">
                <div class="dialogbody">
                    <div class="content">
                        <el-form :rules="addArticleValidate" :model="article" ref="addarticle">
                            <el-form-item prop="articleTitle">
                                <el-input v-model="article.articleTitle" placeholder="请输入文章标题"></el-input>
                            </el-form-item>

                            <el-form-item label="选择分类:" label-width="120px" prop="categoryvalue">
                                <el-col :span="12" style="text-align: left">
                                    <el-select v-model="article.categoryvalue" placeholder="请选择">
                                        <el-option
                                                v-for="(item,index) in options"
                                                :key="index"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-col>


                            </el-form-item>
                            <el-form-item label="选择关联文章:" label-width="120px">
                                <el-col :span="24" style="text-align: left">
                                    <el-select v-model="article.productId" placeholder="请选择">
                                        <el-option-group
                                                v-for="group in articleoptions"
                                                :key="group.label"
                                                :label="group.label">
                                            <el-option
                                                    v-for="item in group.options"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-option-group>
                                    </el-select>
                                </el-col>
                            </el-form-item>


                            <el-form-item label="标  签:" label-width="120px" prop="dynamicTags">
                                <el-col :span="24" style="text-align: left">
                                    <el-tag
                                            :key="tag"
                                            v-for="tag in article.dynamicTags"
                                            closable
                                            :disable-transitions="false"
                                            @close="handleClose(tag)">
                                        {{tag}}
                                    </el-tag>
                                    <el-input
                                            class="input-new-tag"
                                            v-if="inputVisible"
                                            v-model="inputValue"
                                            ref="saveTagInput"
                                            @keyup.enter.native="handleInputConfirm"
                                            @blur="handleInputConfirm"
                                    >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增标签
                                    </el-button>
                                </el-col>

                            </el-form-item>

                            <el-form-item prop="content">
                                <div class="editor">
                                    <tinymce-editor v-model="article.content" :disabled="disabled"
                                                    ref="editor"></tinymce-editor>
                                </div>
                            </el-form-item>

                        </el-form>
                    </div>
                    <div class="submit">
                        <el-button class="submit_button" type="success" @click="submitArticle">提交</el-button>
                        <el-button class="clear_button" type="primary">清空</el-button>
                    </div>
                </div>

            </div>
        </el-dialog>
        <!--        预览文章-->
        <el-dialog :title="dialogDetailTitle"
                   :visible.sync="dialogDetailVisible"
                   :fullscreen="true" @close="dialogDetailClose">
            <div class="articledetail">
                <div class="dialog-body">
                    <div class="title">{{articleDetail.title}}</div>
                    <div class="info">
                        <div class="left">
                            <div class="author">
                                <span>作者：</span>
                                <span>{{articleDetail.loginname}}</span>
                            </div>
                            <div class="tags" v-if="tagshow">
                                <el-tag type="warning" style="margin-right: 5px" size="mini"
                                        v-for="(tag) in articleDetail.tags" :key="tag">{{tag}}
                                </el-tag>
                            </div>
                        </div>

                        <div class="createtime">
                            {{dateFormat('YYYY-mm-dd',articleDetail.createtime)}}
                        </div>

                    </div>
                    <div class="content" v-html="articleDetail.content" @click="imageChgange($event)"></div>
                    <el-dialog title="图片预览(再次点击放大)" :visible.sync="dialogTableVisible" width="680px">
                        <el-image
                                style="width: 600px; height: 400px"
                                :src="url"
                                :preview-src-list="srcList">
                        </el-image>
                    </el-dialog>
                </div>
            </div>

        </el-dialog>
    </div>

</template>

<script>
    import TinymceEditor from '@/components/Tinymce-editor'
    import api from "../../../utils/axios/api"
    import dmzUtil from '../../../utils/DmzUtil'

    export default {
        components: {
            TinymceEditor
        },
        data() {
            return {
                rowHeight:45,
                // dialog模式 0新增 1编辑
                editTag: 0,
                // 发布文章时的选择产品Id选项
                articleoptions: [{
                    label: '热门城市',
                    options: [{
                        value: 'Shanghai',
                        label: '上海'
                    }, {
                        value: 'Beijing',
                        label: '北京'
                    }]
                }, {
                    label: '城市名',
                    options: [{
                        value: 'Chengdu',
                        label: '成都'
                    }, {
                        value: 'Shenzhen',
                        label: '深圳'
                    }, {
                        value: 'Guangzhou',
                        label: '广州'
                    }, {
                        value: 'Dalian',
                        label: '大连'
                    }]
                }],
                // 是否显示详情页中的图片对话框
                dialogTableVisible: false,
                // 图片地址
                url: "",
                // 放大图列表
                srcList: [],
                // 接收文章Id
                id: 0,
                // 文章详情模型
                articleDetail: {
                    createtime: "",
                    title: "",
                    loginname: "",
                    visitor_volume: 0,
                    page_view: 0,
                    content: "",
                    categoryname: "",
                    tags: []
                },
                // 文章显示标题
                dialogDetailTitle: "",
                // 文章显示与否
                dialogDetailVisible: false,
                // 分页信息显示
                displayMsg: "显示 {from} 到 {to} 共计 {total} 项",
                // 分页图标布局
                layout1: [
                    "list",
                    "sep",
                    "first",
                    "links",
                    "prev",
                    "next",
                    "last",
                    "sep",
                    "refresh",
                    "info"
                ],
                // 当前页
                currentPage: 1,
                // 数据总数量
                pageSize: 30,
                total: 0,
                // 文章列表数据
                articlelist: [],
                // 新增文章的表单验证
                addArticleValidate: {
                    articleTitle: [{required: true, trigger: "change", message: "请输入标题"},
                        {
                            validator: function (rule, value, callback) {
                                if (value.length > 18) {
                                    callback(new Error("标题长度太长！"));
                                } else {
                                    callback();
                                }
                            }, trigger: 'change'
                        }
                    ],
                    content: [{required: true, trigger: "change", message: "请输入文章内容"}],
                    categoryvalue: [{required: true, trigger: "change", message: "请选择文章分类"}]
                },
                // 文章的模型
                article: {
                    articleTitle: "",
                    dynamicTags: [],
                    content: "",
                    categoryvalue: 1,
                    productId: 1
                },
                // 搜索模型
                searchModel: {
                    categoryId: 1,
                    keyword: ""
                },
                // 编辑器是否可见
                disabled: false,
                // 文章分类选项
                options: [],
                inputVisible: false,
                inputValue: '',
                // 对话框是否可见
                dialogVisible: false,
                dialogTitle: "添加文章"
            }
        },
        mounted() {
            this.getOptions();
            this.getArticleList();
        },
        methods: {
            // 关闭对话框的回调
            dialogDetailClose(){
                this.resetDetailForm();
                this.resetForm();
            },
             articleDelete(id){
                let _this=this;
                _this.$confirm("确定删除吗 ?", "系统提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(async ()=>{
                    let params={id:id};
                    let {data:res}=await api.deleteArticleById(params);
                    if (res.code == 0) {
                        _this.$message({
                            message: res.msg,
                            type: 'success'
                        })
                    }
                    _this.getArticleList();
                })


            },
            // 点击工具栏编辑按钮
            articleEdit(id) {
                // 新增
                this.editTag = 1;
                this.id = id;
                this.getArticleEditById();
                this.dialogVisible = true;
            },
            // 双击数据表一行时触发事件
            datagridDoubleClick(row) {
                this.id = row.id;
                this.getArticleById();
                this.dialogDetailVisible = true;
            },
            // 根据Id获取文章
            async getArticleById() {
                // let _this=this;
                let param = {id: this.id};
                let {data: res} = await api.getArticleById(param);
                if (res.code == 0) {
                    this.articleDetail.title = res.data.title;
                    this.articleDetail.content = res.data.content;
                    this.articleDetail.tags = res.data.tags.split(",");
                    this.articleDetail.loginname = res.data.user.loginName;
                    this.articleDetail.categoryname = res.data.category.category;
                    this.articleDetail.visitor_volume = res.data.visitorVolume;
                    this.articleDetail.page_view = res.data.pageView;
                    this.articleDetail.createtime = res.data.createTime;
                }
            },
            // 获取编辑的文章详情
            async getArticleEditById() {
                let param = {id: this.id};
                let {data: res} = await api.getArticleById(param);
                if (res.code == 0) {
                    this.article.articleTitle = res.data.title;
                    this.article.content = res.data.content;
                    this.article.dynamicTags = res.data.tags.split(",");
                    this.article.loginname = res.data.user.loginName;
                    this.article.categoryvalue = res.data.categoryId;
                }
            },
            imageChgange(e) {
                if (e.target.nodeName == 'IMG') {
                    this.dialogTableVisible = true;
                    this.srcList = [];
                    this.url = e.target.currentSrc;
                    this.srcList.push(e.target.currentSrc);

                } else {
                    return
                }
            },
            // 格式化日期
            dateFormat(fmt, date) {
                let ret = "";
                date = new Date(date);
                const opt = {
                    'Y+': date.getFullYear().toString(), // 年
                    'm+': (date.getMonth() + 1).toString(), // 月
                    'd+': date.getDate().toString(), // 日
                    'H+': date.getHours().toString(), // 时
                    'M+': date.getMinutes().toString(), // 分
                    'S+': date.getSeconds().toString() // 秒
                    // 有其他格式化字符需求可以继续添加，必须转化成字符串
                }
                for (let k in opt) {
                    ret = new RegExp('(' + k + ')').exec(fmt)
                    if (ret) {
                        fmt = fmt.replace(
                            ret[1],
                            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
                        )
                    }
                }
                return fmt
            },
            // 分页事件
            onPageChange(e) {
                this.currentPage = e.pageNumber;
                this.pageSize = e.pageSize;
                this.articlelist = [];
                this.getArticleList();
            },
            // 新增文章
            addArticle() {
                this.editTag==0;
                this.dialogTitle = "新增文章";
                this.dialogVisible = true;
            },
            // 点击查找文章
            search() {
                this.getArticleList();

            },
            //清空内容
            clear() {
                this.$refs.editor.clear()
            },
            handleClose(tag) {
                this.article.dynamicTags.splice(this.article.dynamicTags.indexOf(tag), 1);
            },

            // 显示分类标签
            showInput() {
                if (this.article.dynamicTags.length >= 3) {
                    this.$message({
                        type: "info",
                        message: "标签数量不能多于3"
                    })
                    return;
                }
                this.inputVisible = true;
                this.$nextTick(() => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    if (this.article.dynamicTags.indexOf(inputValue) != -1) {
                        this.$message({
                            type: "error",
                            message: "标签值重复"
                        })
                        return;
                    }
                    this.article.dynamicTags.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },

            // 获取分类选项
            async getOptions() {
                let _this = this;
                let {data: res} = await api.getCategoryList();
                if (res.code == 0) {
                    let getoption = [];
                    res.data.forEach(p => {
                        let x = {};
                        x.label = p.category;
                        x.value = p.id;
                        getoption.push(x);
                    })
                    _this.options = getoption;
                    // console.log(_this.options);
                }
            },
            // 提交文章
            submitArticle() {
                let _this = this;
                _this.$refs.addarticle.validate(async valid => {
                    let params = {
                        id: _this.id,
                        title: _this.article.articleTitle,
                        categoryId: _this.article.categoryvalue,
                        content: _this.article.content,
                        userId: dmzUtil.getSession("userInfo").id,
                        tags: _this.article.dynamicTags.toString(),
                    }
                    if (valid) {
                        let res = {};
                        if (this.editTag == 0) {
                            res = await api.savearticle(params);

                        }
                        if (this.editTag == 1) {
                            res = await api.updatearticle(params);
                        }
                        if (res.data.code == 0) {
                            _this.$message({
                                type: "success",
                                message: "发表成功"
                            });
                        }
                        // 清空文章模型
                        _this.dialogVisible = false;
                        _this.id = res.data.data;
                        this.getArticleList();
                        setTimeout(function () {
                            _this.dialogDetailTitle = "详情预览";
                            _this.dialogDetailVisible = true;
                            _this.getArticleById();
                        }, 500);
                        // 这里的保存会返回一个文章Id


                    }

                });
            },
            // 初始化表单数据
            resetForm() {
                this.article.articleTitle = "";
                this.article.dynamicTags = [];
                this.article.content = "";
                this.article.categoryvalue = 1;
            },
            resetDetailForm() {
                this.articleDetail.createtime = "";
                this.articleDetail.title = "";
                this.articleDetail.loginname = "";
                this.articleDetail.visitor_volume = 0;
                this.articleDetail.page_view = 0;
                this.articleDetail.content = "";
                this.articleDetail.categoryname = "";
                this.articleDetail.tags = [];
            },
            // 点击分类标签
            tagSelect(item) {
                this.searchModel.categoryId = item.value;
                this.getArticleList();
            },
            // 获取文章列表数据
            async getArticleList() {
                this.articlelist=[];
                let param = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    categoryId: this.searchModel.categoryId,
                    title: this.searchModel.keyword
                };
                let {data: res} = await api.getArticleList(param);
                if (res.code == 0) {
                    res.data.records.forEach(p => {
                        let d = {};
                        d.id = p.id;
                        d.articletitle = p.title;
                        d.articlecategory = p.category.category;
                        d.author = p.user.loginName;
                        d.date = dmzUtil.dateFormat("YYYY-mm-dd", p.createTime);
                        d.pageview = p.visitorVolume;
                        this.articlelist.push(d);
                    });
                    this.total = res.data.total;
                    this.currentPage = res.data.current;
                    this.pageSize = res.data.size;
                }
            }
        },
        computed: {
            // 滚动区高度
            // (业务需求：手机屏幕高度减去头部标题和底部tabbar的高度，当然这2个高度也是可以动态获取的)
            scrollerHeight: function () {
                return (window.innerHeight - 450) + 'px';
            },
            tagshow: function () {
                let self = this;
                return self.articleDetail.tags.length > 1;
            }
        },
    }
</script>

<style scoped lang="scss">
    .body {
        .newlist {
            margin-top: 0;
            padding: 10px;

            .header {
                .title {
                    text-align: left;
                    font: bold 25px arial, sans-serif;
                    height: 60px;
                    line-height: 40px;

                }
            }

            .tool {
                display: flex;
                margin-bottom: 10px;
                justify-content: space-between;

                .toolleft {
                    display: flex;
                    width: 600px;
                }
            }

            .category_tags {
                padding: 10px 0 5px 10px;
            }

            .tt-inner {
                font-size: 14px;
                font-family: "Courier New", Courier, monospace;
                font-weight: bold;
                line-height: 8px;
                width: 60px;
            }
        }

        .dialogdiv {
            display: flex;
            flex-direction: column;

            .dialogbody {
                margin: 0 auto;
                width: 800px;

                .content {
                    border: #DCDFE6 1px solid;
                    padding: 10px;
                    margin-bottom: 20px;

                    .editor {
                        margin-top: 10px;
                    }

                    .el-tag + .el-tag {
                        margin-left: 10px;
                    }

                    .button-new-tag {
                        margin-left: 10px;
                        height: 32px;
                        line-height: 30px;
                        padding-top: 0;
                        padding-bottom: 0;
                    }

                    .input-new-tag {
                        margin-left: 5px;
                        width: 90px;
                        vertical-align: bottom;
                    }
                }

                .submit {
                    display: flex;
                    flex-direction: column;
                    justify-content: center;


                    .submit_button {
                        margin-bottom: 20px;
                    }

                    .clear_button {
                        margin-left: 0;
                        margin-bottom: 20px;
                    }

                    .preview_button {
                        margin-left: 0;
                    }
                }
            }

        }

        .articledetail {
            .dialog-body {
                display: flex;
                flex-direction: column;
                margin: 0 auto;
                width: 750px;

                .title {
                    font-family: "Courier New", Courier, monospace;
                    font-size: 40px;
                    font-weight: bold;
                    height: 100px;
                    line-height: 100px;
                }

                .info {
                    color: #909399;
                    font-size: 14px;
                    margin-top: 15px;
                    height: 20px;
                    display: flex;
                    justify-content: space-between;
                    .left {
                        display: flex;
                        justify-content: flex-start;

                        .tags {
                            height: 20px;
                            margin: 0 10px 0 10px;
                        }

                        .author {
                            line-height: 20px;
                            margin: 0 10px 0 50px;
                        }
                    }

                    .createtime {
                        margin-right: 50px;
                    }


                }
                .content{
                    margin-top: 10px;
                }
            }
        }

    }


</style>
